import _thread
import json
import socket
import sys
from machine import Timer
import time
from .states import states
from .audio import audio, PLAY, RESUME, PAUSE
try:
    from typing import Union
    from shared_types import DownHeartbeatMsg, ControlMsg
except:
    pass
t = Timer(1)


class MsgListener:
    """
    侦听UDP消息
    """

    def __init__(self, port: int) -> None:
        self._th = None
        self.port = port

    def listen(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # 绑定到指定端口
        server_address = ('0.0.0.0', self.port)
        s.bind(server_address)

        print('UDP is listening on', server_address)

        while True:
            try:
                data, address = s.recvfrom(1024)
                msg_data: 'Union[DownHeartbeatMsg, ControlMsg]' = json.loads(
                    data)
                assert isinstance(msg_data, dict)
                assert 'type' in msg_data
                if msg_data['type'] == 'ETT_HEARTBEAT_DOWN':
                    states.connection_status = 'connected'
                    states.last_keepalive_time = time.time()
                elif msg_data['type'] == 'ETT_DEVICE_CONTROL':
                    payload = msg_data['payload']
                    if payload['kind'] == "audio":
                        if payload['cmd'] == "play":
                            audio.state = PLAY
                        elif payload['cmd'] == "stop":
                            audio.state = PAUSE
                        else:
                            print(f"cannot recognize audio command {payload['cmd']}")
            except Exception as e:
                sys.print_exception(e)

    def start(self):
        """
        Start listening to socket
        """
        self._th = _thread.start_new_thread(self.listen, ())
